<template>
  <div>
    <!-- el-dialog内部也有一个 this.$emit('update:visible') -->
    <!-- 出现bug的原因 是因为 el-dialog中的visible.sync 的值 来自 add-dept组件的父组件， -->
    <!-- 如果visible.sync 的值 是add-dept本身的值 就不会有问题了 -->
    <el-dialog :title="showTitle" :visible.sync="dialogVisible" @close="closeHandle">
      <!-- 表单组件  el-form   label-width设置label的宽度   -->
      <!-- 匿名插槽 -->
      <el-form ref="addFormRef" label-width="120px" :model="formData" :rules="formDataRules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeeSimple">
            <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username" />
          </el-select>

        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
      <el-row slot="footer" type="flex" justify="center">
        <!-- 列被分为24 -->
        <el-col :span="6">
          <el-button type="primary" size="small" @click="addHandle">确定</el-button>
          <el-button size="small" @click="closeHandle">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import {
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'
export default {
  model: {
    prop: 'showDialog',
    event: 'changeShowDialog'
  },
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    treeNode: {
      type: Object,
      required: true
    },
    departList: {
      type: Array,
      required: true
    }
  },
  data() {
    const checkName = (rule, value, cb) => {
      // 获取当前部门中 所有的子部门
      // 用最新的部门名称跟其他的子部门名称对比
      let isRepeat
      if (this.formData.id) {
        isRepeat = this.departList
          .filter(
            item =>
              item.id !== this.formData.id && item.pid === this.treeNode.pid
          )
          .some(item => item.name === value)
      } else {
        isRepeat = this.departList
          .filter(item => item.pid === this.treeNode.id)
          .some(item => item.name === value)
      }

      isRepeat ? cb(new Error(`同级部门下已经有${value}的部门了`)) : cb()
    }
    return {
      dialogVisible: false,
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      peoples: [],
      formDataRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增子部门'
    }
  },
  watch: {
    showDialog: function(val) {
      console.log(val)
      this.dialogVisible = val
    }
  },
  mounted() {
    this.dialogVisible = this.showDialog
  },
  methods: {
    // 获取员工简单列表数据
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple()
    },
    addHandle() {
      // 获取 el-form 实例 调用 预校验的方法
      this.$refs.addFormRef.validate(async vali => {
        if (vali) {
          if (this.formData.id) {
            await updateDepartments(this.formData)
          } else {
            // 发起添加请求
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }

          this.$message.success('操作成功')
          // 通知父组件更新数据
          this.$emit('addNewChild')
        }
      })
    },
    closeHandle() {
      // 重置数据  因为resetFields 只能重置 表单上的数据 非表单上的 比如 编辑中id 不能重置
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$refs.addFormRef.resetFields()
      this.$emit('update:showDialog', false)
    },
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
